// 密码（禁止输入中文和空格）
export const inputPwd = function (string) {
  let upwd = string.replace(/[\u4e00-\u9fa5]|\s+/g, '');
  return upwd;
}
/**
 * Created by jiachenpan on 16/11/18.
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}
export function isvalidUsername (str) {
  const valid_map = ['admin', 'editor']
  return valid_map.indexOf(str.trim()) >= 0
}

/* 合法uri */
export function validateURL (textval) {
  const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return urlregex.test(textval)
}

/* 小写字母 */
export function validateLowerCase (str) {
  const reg = /^[a-z]+$/
  return reg.test(str)
}

/* 大写字母 */
export function validateUpperCase (str) {
  const reg = /^[A-Z]+$/
  return reg.test(str)
}

/* 大小写字母 */
export function validateAlphabets (str) {
  const reg = /^[A-Za-z]+$/
  return reg.test(str)
}

/**
 * validate email
 * @param email
 * @returns {boolean}
 */
export function validateEmail (email) {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return re.test(email)
}
// 输入验证器名称
export function selectvalidator (name) {
  const fn = eval(name)
  const rules = []
  rules.push({ validator: fn, message: '', trigger: 'blur' })
  return rules
}
// 验证长度
export function length (from, to) {
  const rules = []
  rules.push({ min: from, max: to, message: '长度在' + from + ' 到' + to + '个字符', trigger: 'blur' })
  return rules
}
// 字符串不能为空
export function isNotNull (msg) {
  const rules = []
  rules.push({ required: true, message: msg, trigger: 'blur' })
  return rules
}
/* 是否固话 */
export function validateTelphone (rule, value, callback) {
  const reg = /[0]\d{2,3}[-]\d{7,8}$/
  if (value === '' || value === undefined || value == null) {
    callback()
  } else {
    if ((!reg.test(value)) && value !== '') {
      callback(new Error('请输入正确的固话（格式：区号+号码,如010-1234567）'))
    } else {
      callback()
    }
  }
}
/* 是否手机号码 */
export function validatePhone (rule, value, callback) {
  const reg = /^[1][3,4,5,7,8][0-9]{9}$/
  if (value === '' || value === undefined || value == null) {
    callback()
  } else {
    if ((!reg.test(value)) && value !== '') {
      callback(new Error('请输入正确的电话号码'))
    } else {
      callback()
    }
  }
}
/* 是否身份证号码 */
/* export function validateIdNo(rule, value, callback) {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (value === '' || value === undefined || value === null) {
    callback()
  } else {
    if ((!reg.test(value)) && value !== '') {
      callback(new Error('请输入正确的身份证号码'))
    } else {
      callback()
    }
  }
} */

/* 是否身份证号码 */
export function validateIdNo (rule, value, callback) {
  if (value === '' || value === undefined || value === null) {
    callback()
  } else {
    if (!IdentityCodeValid(value)) {
      callback(new Error('请输入正确的身份证号码'))
    } else {
      callback()
    }
  }
}

function IdentityCodeValid (code) {
  var city = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江 ', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北 ', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏 ', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外 ' }
  var pass = true

  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    pass = false
  } else if (!city[code.substr(0, 2)]) {
    pass = false
  } else {
    // 18位身份证需要验证最后一位校验位
    if (code.length == 18) {
      code = code.split('')
      // ∑(ai×Wi)(mod 11)
      // 加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      // 校验位
      var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
      var sum = 0
      var ai = 0
      var wi = 0
      for (var i = 0; i < 17; i++) {
        ai = code[i]
        wi = factor[i]
        sum += ai * wi
      }
      var last = parity[sum % 11]
      if (parity[sum % 11] != code[17]) {
        pass = false
      }
    }
  }
  return pass
}
/* 是否邮箱 */
export function isEMail (rule, value, callback) {
  const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/
  if (value === '' || value === undefined || value === null) {
    callback()
  } else {
    if (!reg.test(value)) {
      callback(new Error('请输入正确的邮箱地址'))
    } else {
      callback()
    }
  }
}

/* 合法url */
export function isUrl (rule, value, callback) {
  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  if (value === '' || value === undefined || value === null) {
    callback()
  } else {
    if (!reg.test(value)) {
      callback(new Error('请输入正确的url'))
    } else {
      callback()
    }
  }
}

// 身份证 ,手机 （禁止空格且只能输入数字）
export const inputPhone = function (string) {
  let uphone = string.replace(/\D/g, '').replace(/\s/g, '');
  return uphone;
}

export const banSpan = function (string) { // 禁止输入空格
  let uphone = string.replace(/\s/g, '');
  return uphone;
}
// 禁止输入特殊字符 patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im
export const inputTY = function (string) {
  let patrn = string.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/img, '').replace(/\s/g, '');
  return patrn;
}

// 邮箱校验
export const inputEmail = function (string) {
  let email = string.replace(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/);
  return email;
}

// 设置数字范围在0-100
export const inputSimilar = function (string) {
  let usim = string.replace(/\D/g, '').replace(/\s/g, '');
  if (usim > 100) {
    if (usim.slice(0, 2) <= 10) {
      return usim.slice(0, 3);
    } else {
      return usim.slice(0, 2);
    }
  } else {
    return usim;
  }
}
//  设置只能正数字
export const inputNumberZ = function (string) {
  let uphone = string.replace(/\D/g, '').replace(/\s/g, '');
  return uphone;
}
//  设置只能数字英文
export const inputNumberEng = function (string) {
  string = string.replace(/[^(A-Za-z0-9)]+/ig, '');
  return string
}
//  设置只能数字-
export const inputNumberCode = function (string) {
  string = string.replace(/[^\d\-]/g, '');
  return string
}
//  设置只能数字:
export const inputMacCode = function (string) {
  string = string.replace(/[^\d\:]/g, '');
  return string
}
//  设置只能数字小数
export const inputNumber = function (string) {
  var t = string.charAt(0);
  // 先把非数字的都替换掉，除了数字和.
  string = string.replace(/[^\d.]/g, '');
  // 必须保证第一个为数字而不是.
  string = string.replace(/^\./g, '');
  // 保证只有出现一个.而没有多个.
  string = string.replace(/\.{2,}/g, '.');
  // 保证.只出现一次，而不能出现两次以上
  string = string.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
  // 保证小数限制
  string = string.replace(/^(\-)*(\d+)\.(\d\d\d\d\d).*$/, '$1$2.$3');
  // 如果第一位是负号，则允许添加   如果不允许添加负号 可以把这块注释掉
  if (t === '-') {
    string = '-' + string;
  }
  return string
}

// id号码校验
export const inputIdcard = function (string) {
  var pattern = /^.{15,18}$/;
  let uphone = pattern.test(string.replace(' ', ''));
  return uphone;
}
// 获取生日 .replace(/-/g, '/')
export const inputBirth = function (idCard) {
  var birthday = '';
  if (idCard !== null && idCard !== '' && idCard.length >= 14) {
    let dateTime = idCard.substring(6, 14);
    if (typeof (dateTime - 0) === 'number') {
      let year = dateTime.substring(0, 4);
      let month = dateTime.substring(4, 6);
      let days = dateTime.substring(6, 8)
      let date = year + '-' + month + '-' + days;
      if (new Date(date).getFullYear() === year - 0 && new Date(date).getMonth() === month - 1 && new Date(date).getDate() === days - 0) {
        birthday = date.replace(/-/g, '/')
      }
    } else {
      birthday = null;
    }
  }

  return birthday;
}
// LonLat
export const inputLonLat = function (string) {
  var pattern = /^[0-9]+.?[0-9]+$/;
  let uphone = true;
  if (string !== '') {
    uphone = pattern.test(string.replace(' ', ''));
  }
  return uphone;
}
// 车牌号校验
export const inputCarid = function (string) {
  var pattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领a-zA-Z]{1}[a-zA-Z]{1}[a-zA-Z0-9]{4}[a-zA-Z0-9挂学警港澳]{1}$/;
  let uphone = pattern.test(string.replace(' ', ''));
  return uphone;
}

// mac地址校验
export const inputMacId = function (string) {
  var pattern = /[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
  let uphone = pattern.test(string.replace(' ', ''));
  return uphone;
}

// 将空格转换为不空格
export const inputUsename = function (string) {
  let uphone = string.replace(/\s*/g, '')
  return uphone;
}

// 密码复杂性校验
export const pwdComplex = function (string) {
  let i = 0;
  if (string.match(/([a-z])+/)) {
    i++;
  }
  if (string.match(/([0-9])+/)) {
    i++;
  }
  if (string.match(/([A-Z])+/)) {
    i++;
  }
  if (string.match(/[^a-zA-Z0-9]+/)) {
    i++;
  }
  return i;
}
